<?php

namespace App\Http\Controllers\EmberApi;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Pool\DataReader;
use Illuminate\Support\Facades\DB;
use App\Pool\Statistics\Parser as StatisticsParser;
use App\Pool\Miners\Parser as MinersParser;
use App\Miners\Miner;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

class AccountsController extends Controller
{
    //
    public function index(Request $request){
        //var_dump($address);
        //通过矿工地址查询到miners表中对应的记录
        //$address = urldecode($address);
        $requestUri = $request->getRequestUri();
        $requestPath = '/'.$request->path().'/?address=';
        $address = substr($requestUri,strlen($requestPath));
        //var_dump($address);
        //
        $cache = Redis::get($address);
        $stats = json_encode([]);
        if(!isset($cache)){
            $stats = $this->getData($address);
            Redis::setex($address,60,$stats);
            $stats = json_decode($stats);
        }else{
            $stats = json_decode($cache);
        }
        return response()->json($stats);
    }


    protected function getData($address){


        $minerInfo = DB::table('miners')
            ->where('address',$address)
            ->first();

        //如果能查询到对应的记录则继续构造api需返回的json数据，否则直接返回一个初始化json数据
        if (isset($minerInfo)){
            //var_dump($minerInfo);

            //将miners表中对应的字段数据填充到构造json数据数组中
            $jsonArray = [];
            //分页大小
            $jsonArray['pageSize'] = 30;
            //30分钟平均算力值
            $jsonArray['currentHashrate'] = $minerInfo->hashrate;
            //3小时平均算力值
            $jsonArray['hashrate'] = $minerInfo->average_hashrate;
            //未支付的贡献值
            $jsonArray['unpaidShares'] = $minerInfo->unpaid_shares;

            //矿池支付的总金额
            $jsonArray['stats']['paid'] = $minerInfo->earned;
            //今日支付金额
            $jsonArray['stats']['payToday'] = $minerInfo->pay_today;
            //昨天支付金额
            $jsonArray['stats']['payYesterday'] = $minerInfo->pay_yesterday;
            //矿工钱包余额
            $jsonArray['stats']['balance'] = $minerInfo->balance;

            //矿工钱包余额更新时间
            $jsonArray['stats']['balanceUpdated'] = strtotime($minerInfo->balance_updated_at);

            //将payouts表中对应的字段数据填充到构造json数据数组中
            $paymentsTotal = DB::table('payouts')
                ->where('recipient',$address)
                ->count();
            //总支付次数
            $jsonArray['paymentsTotal'] = $paymentsTotal;
            //支付记录数据
            $payments = DB::table('payouts')
                ->where('recipient',$address)
                ->latest('made_at')
                ->limit(50)
                ->get();
            $i = 0;
            //var_dump($payments);
            foreach ($payments as $payment) {
                //var_dump($this->getBlockhash($payment->found_block_id));
                $jsonArray['payments'][$i]['amount'] = $payment->amount;
                $jsonArray['payments'][$i]['timestamp'] = strtotime($payment->made_at);
                $jsonArray['payments'][$i]['tx'] = $this->getBlockhash($payment->found_block_id);
                $i++;
            }

            //填充workers数据
            $workersOnlineData = [];
            $workersOfflineData = [];
            //查询当前矿工的所有矿机
            $minerWorkers = DB::table('miner_workers')
                ->where('address',$address)
                //->orderBy('worker_name','asc')
                ->get();

            //构造矿机数组
            foreach ($minerWorkers as $minerWorker) {
                $updateDate = $minerWorker->updated_at;
                $lastBeat = strtotime($updateDate);
                $timeNow = Carbon::now();
                $hr = $minerWorker->worker_hash;
                if ($minerWorker->status == 'active' && $timeNow->diffInMinutes(new Carbon($updateDate)) < 5){
                    $workersOnlineData[$minerWorker->worker_name]['lastBeat'] = $lastBeat;
                    $workersOnlineData[$minerWorker->worker_name]['hr'] = $hr;
                    $workersOnlineData[$minerWorker->worker_name]['offline'] = false;
                }else{
                    if ($timeNow->diffInHours(new Carbon($updateDate)) < 24){
                        $workersOfflineData[$minerWorker->worker_name]['lastBeat'] = $lastBeat;
                        $workersOfflineData[$minerWorker->worker_name]['hr'] = 0;
                        $workersOfflineData[$minerWorker->worker_name]['offline'] = true;
                    }

                }
            }
            ksort($workersOnlineData,SORT_NATURAL | SORT_FLAG_CASE);
            ksort($workersOfflineData,SORT_NATURAL | SORT_FLAG_CASE);
            //在线机器数量
            $workerOnlineCount = count($workersOnlineData);
            $jsonArray['workersOnlineCount'] = $workerOnlineCount;
            //离线机器数量
            $workerOfflineCount = count($workersOfflineData);
            $jsonArray['workersOfflineCount'] = $workerOfflineCount;
            $jsonArray['workersTotal'] = $workerOnlineCount + $workerOfflineCount;
            $jsonArray['workers_online'] = $workersOnlineData;
            $jsonArray['workers_offline'] = $workersOfflineData;

            //return response()->json($jsonArray);
            return json_encode($jsonArray);
        }else{
            //return response()->json([]);
            return json_encode([]);
        }

    }


    protected function getBlockhash($blockid){
        $blockHash = DB::table('found_blocks')
            ->where('id',$blockid)
            ->first(['hash']);
        return $blockHash->hash;
    }
}
